/**
 * Copyright:Copyright(c)2014-2017
 * Company:厦门市易致达物联网科技有限公司
 * @version 1.0
 */
package shop.controller.manage.testproject;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import shop.core.common.bean.JSONResult;
import shop.core.common.bean.ManageContainer;
import shop.core.util.ExcelUtils;
import shop.core.util.KeyValueHelper;
import shop.core.Services;
import shop.core.util.MD5;
import shop.core.util.StrUtils;
import shop.services.manage.system.bean.User;
import shop.services.manage.testproject.TestprojectService;
import shop.services.manage.testproject.bean.Testproject;
import shop.core.BaseController;
import shop.core.RequestHolder;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.IntrospectionException;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**   
 * @类名称：TestprojectAction      
 * @创建人：wzl
 * @创建时间：2018-05-24 下午15:17:35      
 * @版本号：1.0
 * @描述：     
 */
@Controller
@RequestMapping("/manage/testproject/")
public class TestprojectAction extends BaseController<Testproject> {
    private static final Logger logger = LoggerFactory.getLogger(TestprojectAction.class);
    @Autowired
    private TestprojectService testprojectService;
    private static final String page_toList = "/manage/testproject/testprojectList";
    private static final String page_toAdd = "/manage/testproject/testprojectAdd";
    private static final String page_toEdit = "/manage/testproject/testprojectEdit";
    public TestprojectService getService() {
        return testprojectService;
    }

    private TestprojectAction(){
        super.page_toList = page_toList;
        super.page_toAdd = page_toAdd;
        super.page_toEdit = page_toEdit;
    }



    /**
     * excel文件导入
     */
    @RequestMapping(value = "excelUpload")
    public void upload(HttpServletRequest request, HttpServletResponse response, Testproject testproject) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        //获得文件
        MultipartFile file = multipartRequest.getFile("file");
        if (file.isEmpty()) {
            throw new Exception("文件不存在！");
        }
        //获得输入流
        InputStream in = file.getInputStream();
        List<List<Object>> listob = ExcelUtils.getBankListByExcel(in, file.getOriginalFilename());
        List<Testproject> testprojectList = new ArrayList<>();
        Testproject creditInfoBean = null;
        for (int i = 0, length = listob.size(); i < length; i++) {
            List<Object> ob = listob.get(i);
            creditInfoBean = new Testproject();
            creditInfoBean.setCategoryID(String.valueOf(ob.get(0)));
            creditInfoBean.setName(String.valueOf(ob.get(1)));
            String str = String.valueOf(ob.get(2));
            //判断字符串为空或者字符串不是数字
            if(StringUtils.isEmpty(str)||!StrUtils.isInteger(str)){
                str="0.0";
            }
            BigDecimal bd = new BigDecimal(str);
            creditInfoBean.setPrice(bd);
            creditInfoBean.setAccordingTo(String.valueOf(ob.get(3)));
            creditInfoBean.setDetectionLimit(String.valueOf(ob.get(4)));
            creditInfoBean.setDetectionLimitUnit(String.valueOf(ob.get(5)));
            creditInfoBean.setAptitude(String.valueOf(ob.get(6)));
            creditInfoBean.setTestMethod(String.valueOf(ob.get(7)));
            creditInfoBean.setRemark(String.valueOf(ob.get(8)));
            testprojectList.add(creditInfoBean);
        }
        testprojectService.insertList(testprojectList);
        in.close();
        PrintWriter out = null;
        response.setCharacterEncoding("utf-8");  //防止ajax接受到的中文信息乱码
        out = response.getWriter();
        out.print("文件导入成功！");
        out.flush();
        out.close();
    }

    /**
     * excel文件导出
     */
    @RequestMapping(value = "excelDownload", method = RequestMethod.GET)
    public void outExcel(HttpServletRequest request, HttpServletResponse response, Testproject testproject) throws InvocationTargetException, ClassNotFoundException, IntrospectionException, ParseException, IllegalAccessException {
        response.reset();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssms");
        String dateStr = sdf.format(new Date());
        // 指定下载的文件名
        response.setHeader("Content-Disposition", "attachment;filename=" + dateStr + ".xlsx");
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        logger.debug("查询数据库开始时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        List<Testproject> creditInfoList = testprojectService.selectList(testproject);
        logger.debug("查询数据库结束时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        List<Testproject> ems = new ArrayList<>();
        Map<Integer, List<Testproject>> maps = new LinkedHashMap<>();
        SXSSFWorkbook book = null;
        ems.add(new Testproject("目录", "categoryName", 0));
        ems.add(new Testproject("项目名称", "name", 0));
        ems.add(new Testproject("价格", "price", 0));
        ems.add(new Testproject("方法依据", "accordingTo", 0));
        ems.add(new Testproject("检出限", "detectionLimit", 0));
        ems.add(new Testproject("检出限单位", "detectionLimitUnit", 0));
        ems.add(new Testproject("资质", "aptitude", 0));
        ems.add(new Testproject("检测方法", "testMethod", 0));
        ems.add(new Testproject("备注", "remark", 0));
        maps.put(0, ems);
        try {
            logger.debug("创建文件开始时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            book = ExcelUtils.createExcelFile(Testproject.class, creditInfoList, maps, "销售表");
            logger.debug("创建文件结束时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        } catch (IllegalArgumentException | IllegalAccessException
                | InvocationTargetException | ClassNotFoundException
                | IntrospectionException | ParseException e1) {
            e1.printStackTrace();
        }
        OutputStream output;
        try {
            output = response.getOutputStream();

            BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
            //刷新此缓冲的输出流，保证数据全部都能写出
            bufferedOutPut.flush();
            book.write(bufferedOutPut);
            bufferedOutPut.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
